package com.gemini.main.cglib;

import net.sf.cglib.proxy.*;

import java.lang.reflect.Method;


public class CglibLeak {

    public <T> T newProxyInstance(Class<T> clazz) {
        return newProxyInstance(clazz, new MyInterceptor(), new MyFilter());
    }

    public static <T> T newProxyInstance(Class<T> superclass, Callback methodCb, CallbackFilter callbackFilter) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(superclass);
        enhancer.setCallbacks(new Callback[]{methodCb, NoOp.INSTANCE});
        enhancer.setCallbackFilter(callbackFilter);

        return (T) enhancer.create();
    }

    class MyInterceptor implements MethodInterceptor {
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            return null;
        }
    }

    class MyFilter implements CallbackFilter {

        @Override
        public int accept(Method method) {
            return 0;
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof MyFilter) {
                return true;
            }
            return false;
        }

        @Override
        public int hashCode() {
            return 10011; // 没什么原则，只为测试
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CglibLeak leak = new CglibLeak();
        int count = 0;
        while (true) {
            leak.newProxyInstance(Object.class);
            Thread.sleep(100);
            System.out.println(count++);
        }
    }
}
